﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using UploadFile.Common;
using UploadFile.Models;

namespace UploadFile.Controllers
{
    [Produces("application/json")]
    [Consumes("application/json", "multipart/form-data")]//此处为新增
    [Route("api/[controller]")]
    [ApiController]
    public class UploadFileController : ControllerBase
    {
        private readonly ICrudProvider _crudProvider;
        private readonly IHostingEnvironment _hostingEnvironment;
        private readonly IHttpContextAccessor _accessor;

        public UploadFileController(ICrudProvider crudProvider, IHostingEnvironment hostingEnvironment, IHttpContextAccessor accessor)
        {
            this._crudProvider = crudProvider;
            this._hostingEnvironment = hostingEnvironment;
            this._accessor = accessor;
        }

        [HttpPost("File")]
        [RequestSizeLimit(1024 * 1024 * 1024)] //字节
        //[DisableRequestSizeLimit]  //或者取消大小的限制
        public async Task<ActionResult> Post(IFormFileCollection files)
        {
            long size = files.Sum(f => f.Length);
            var fileFolder = Path.Combine(_hostingEnvironment.WebRootPath, "Files", DateTime.Now.ToString("yyyyMMdd"));
            if (!Directory.Exists(fileFolder))
                Directory.CreateDirectory(fileFolder);

            FileData fileData = new FileData();
            List<Dictionary<string, string>> retFileInfo = new List<Dictionary<string, string>>();
            Dictionary<string, string> fileInfo = new Dictionary<string, string>();
            foreach (var formFile in files)
            {
                if (formFile.Length > 0)
                {
                    // 上传文件 名称
                    //var uploadedFileName = formFile.FileName;
                    var uploadedFileName = formFile.FileName.Split('\\')[formFile.FileName.Split('\\').Length - 1];
                    // 上传文件 类型
                    var uploadedFileType = Path.GetExtension(formFile.FileName);
                    var fileGuid = Guid.NewGuid();
                    var fileName = $"{fileGuid}(ง •_•)ง{uploadedFileName}";
                    //var fileName = uploadedFileName;
                    var filePath = Path.Combine(fileFolder, fileName);
                    using (var stream = new FileStream(filePath, FileMode.Create))
                    {
                        await formFile.CopyToAsync(stream);
                    }
                    //相关信息 存储到数据库
                    fileData.Id = Guid.Empty;
                    //fileData.Id = fileGuid;
                    fileData.FileGuid = fileGuid;
                    fileData.FileName = uploadedFileName;
                    fileData.FilePath = filePath;
                    fileData.UploadDate = DateTime.Now;
                    fileData.IPAddress = _accessor.HttpContext.Connection.RemoteIpAddress.ToString();

                    await _crudProvider.AddAsync(fileData);
                    fileInfo = new Dictionary<string, string>();
                    fileInfo.Add("fileId", fileData.Id.ToString());
                    fileInfo.Add("fileName", fileData.FileName);
                    retFileInfo.Add(fileInfo);
                }
            }
            return Ok(new { count = files.Count, size ,fileInfo = retFileInfo });
        }

        ///// <summary>
        ///// 获取客户Ip
        ///// </summary>
        ///// <param name="context"></param>
        ///// <returns></returns>
        //public string GetClientUserIp(this HttpContext context)
        //{
        //    string ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault();
        //    if (string.IsNullOrEmpty(ip))
        //    {
        //        ip = context.Connection.RemoteIpAddress.ToString();
        //    }
        //    return ip;
        //}


    }
}